package base.jfinal.plugin;

import base.jfinal.anatation.RouteBind;
import base.jfinal.anatation.TimerBind;
import base.util.PropertiesContent;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.config.Routes;

import java.io.File;
import java.util.List;

/**
 * Routes 工具类 自动绑定Controller
 */
public class RoutesUtil{
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void add(Routes me){
		List<Class> list= ClassSearcher.findClass("/em/ctrl");

		if(list!=null&&list.isEmpty()==false){
			for(Class clz:list){
				RouteBind rb=(RouteBind)clz.getAnnotation(RouteBind.class);
				if(rb!=null){
					String clzDir=(new File(clz.getResource("").getPath())).getName();
					if("ctrl".equals(clzDir)){
						clzDir="";
					}else{
						clzDir+="/";
					}
					String route = PropertiesContent.get("jfinal.basepath","");
					route += rb.path().startsWith("/")?rb.path():(clzDir+rb.path());
					System.out.println("Add Route:"+route + " Class:" + clz.getName() + " ViewPath:" + rb.viewPath());
					me.add(route,clz,rb.viewPath());
				}
			}
		}
	}
	
	/**
	 * 取得定时器类
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked", "unused" })
	public static JSONArray GetClass(){
		JSONArray jsons=new JSONArray();
		List<Class> list=ClassSearcher.findClass("/em/job");
		JSONObject json;
		if(list!=null && !list.isEmpty()){
			for(Class clz:list){
				TimerBind tb=(TimerBind)clz.getAnnotation(TimerBind.class);
				if(tb!=null){
					json=new JSONObject();
					json.put("ClassSpace", tb.ClassSpace());
					json.put("Cron", tb.Cron());
					json.put("Enable", tb.Enable());
					jsons.add(json);
				}
			}
		}
		return jsons;
	}
}
